﻿/*
 ***************************************************************************
 * Microsoft Visual C# .NET
 * 名称：       App_Input_SaleProcessPresentForm
 * 类型：       控制层
 * 功能说明：   销售过程-礼品发放页面
 * 作者：       章 昕
 * 创建日期：   2007/08/30
 * 修改日期     修改者      修改内容
 * 
 * 
 * ---
 ***************************************************************************
*/

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Shpm.App.Input.Dao;
using Shpm.App.Input.Bean;
using Shpm.App.Commons.Db.Beans.Master;
using Shpm.App.Commons.Db.Beans.Inp;
using Shpm.App.Commons.Utils;
using Shpm.System.Web.Control;
using log4net;
using System.Text.RegularExpressions;
using Shpm.System;
using Shpm.App.Commons.Utils;

public partial class App_Input_SaleProcessPresentForm : System.Web.UI.Page
{
    // log
    protected static ILog log = LogManager.GetLogger(typeof(App_Input_SaleProcessPresentForm));

    // constant

    // 礼品数量 TextBox
    private const string TEMPLATE_CONTROL_TEXTBOX = "txtGiftNum";
    // 选择 CheckBox
    private const string TEMPLATE_CONTROL_CHECKBOX = "ckbCheck";

    // page load
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!Page.IsPostBack)
            {
                // 流ID
                this.ViewState["PROC_ID"] = "";
                // 流取消Flg
                this.ViewState["CANCEL_FLG"] = null;
                // 流当前步序
                //this.ViewState["CUR_STEP"] = null;

                if (Context.Items["SALE_PROC_ID"] != null)
                {
                    this.ViewState["PROC_ID"] = Convert.ToString(Context.Items["SALE_PROC_ID"]);
                }

                // load exist data
                Boolean blnFindData = false;
                if (this.ViewState["PROC_ID"].ToString().Length > 0)
                {
                    blnFindData = bindSelectData(this.ViewState["PROC_ID"].ToString());
                }

                if (Context.Items.Contains("RIGHT"))
                    ViewState["RIGHT"] = Context.Items["RIGHT"];

            }
        }
        catch (Exception ex)
        {
            log.Fatal(ex.StackTrace);
            log.Fatal(ex.Message);
            throw ex;
        }
    }

    // before render
    void Page_PreRender(object sender, EventArgs e)
    {
        // 销售过程跟踪 link 状态
        //setLinkStatus();
    }

    // 登记按钮
    protected void btnOk_Click(object sender, EventArgs e)
    {
        try
        {
            // check is allow update
            if (!ComValidator1.DoValidator())
            {
                ((Design_MasterPage)this.Master).InfoMessage = ComValidator1.ErrorMessage;
                return;
            }

            SaleProcessDao dao = new SaleProcessDao();
            SysUserManager manager = new SysUserManager(Context);
            SysUserBean sysUserBean = manager.getSysUserBean();
            MstSysUserBean mstSysUserBean =
                sysUserBean == null ? null : sysUserBean.getMstSysUserBean();
            MstEmployeeBean mstEmpBean =
                sysUserBean == null ? null : sysUserBean.getEmployeeBean();
            string loginId = mstSysUserBean == null ? "" : mstSysUserBean.SysUserId;
            string emplyId = mstSysUserBean == null ? "" : mstSysUserBean.EmployeeId;
            string emplyRole = mstEmpBean == null ? "" : mstEmpBean.Role;

            // 权限check
            if (!checkAuthority(this.ViewState["PROC_ID"].ToString(), emplyId, emplyRole))
            {
                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0901").ToString();
                return;
            }

            // 更新
            SaleProcessBean beanSP = new SaleProcessBean();
            beanSP.SaleProcId = Convert.ToInt32(this.ViewState["PROC_ID"].ToString());
            beanSP = dao.FindBySaleProcess(beanSP);
            if (beanSP == null)
            {
                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0005").ToString();
                return;
            }

            // set form element to bean
            //if (beanSP.CurrentStep != null
            //    && beanSP.CurrentStep == SaleProcessDao.SALE_PROCESS_STEP_5)
            //{
            //    beanSP.CurrentStep = SaleProcessDao.SALE_PROCESS_STEP_6;
            //}
            beanSP.UserId = loginId;

            IList listGift = null;
            listGift = new ArrayList();
            for (int i = 0; i < viewGift.Rows.Count; i++)
            {
                CheckBox check = (CheckBox)viewGift.Rows[i].FindControl(TEMPLATE_CONTROL_CHECKBOX);
                TextBox numGift = (TextBox)viewGift.Rows[i].FindControl(TEMPLATE_CONTROL_TEXTBOX);
                if (check != null && check.Checked)
                {
                    if (!string.IsNullOrEmpty(numGift.Text) && !this.checkGiftNum(numGift.Text))
                    {
                        ((Design_MasterPage)this.Master).InfoMessage =
                            (HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0322").ToString()).Replace("{0}", "礼品数量");
                        return;
                    }
                    SalesGiftBean beanGift = new SalesGiftBean();
                    beanGift.GiftId = Convert.ToInt32(viewGift.DataKeys[i].Value);
                    beanGift.Quantity = string.IsNullOrEmpty(numGift.Text) ? 0 : Convert.ToInt32(numGift.Text);
                    beanGift.UserId = loginId;
                    listGift.Add(beanGift);
                }
            }
            log.Info("***** Start UPDATE INSERT *****");
            dao.UpdProcInsSalesGift(beanSP, listGift);
            this.ViewState["CUR_STEP"] = beanSP.CurrentStep;
            ((Design_MasterPage)this.Master).InfoMessage =
                HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0002").ToString();

        }
        catch (Exception ex)
        {
            log.Fatal(ex.StackTrace);
            log.Fatal(ex.Message);
            throw ex;
        }
    }

    // check num
    private Boolean checkGiftNum(string number)
    {
        CheckLong chklong = new CheckLong(number);
        return chklong.doCheck();
    }


    // adjust bind data
    protected void viewGift_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            SalesGiftBean beanGift = (SalesGiftBean)e.Row.DataItem;
            ((TextBox)e.Row.FindControl(TEMPLATE_CONTROL_TEXTBOX)).Text = Convert.ToString(beanGift.Quantity);
            ((CheckBox)e.Row.FindControl(TEMPLATE_CONTROL_CHECKBOX)).Checked = beanGift.SaleProcId != null;
        }
    }

    //// link 按钮 click
    //protected void lnkBtn_Command(object sender, CommandEventArgs e)
    //{
    //    string directUrl = "~/App/Search/SaleProcSrhForm.aspx";
    //    switch (e.CommandName)
    //    {
    //        case "btn0":
    //            // 销售开始                
    //            directUrl = "~/App/Input/SaleProcessBeginForm.aspx";
    //            break;
    //        case "btn1":
    //            // 入会登记
    //            directUrl = "~/App/Input/SaleProcesseMembershipForm.aspx";
    //            break;
    //        case "btn2":
    //            // 体检报告
    //            directUrl = "~/App/Input/SaleProcessHealthForm.aspx";
    //            break;
    //        case "btn3":
    //            // 资格审核
    //            directUrl = "~/App/Input/SaleProcessIndefinForm.aspx";
    //            break;
    //        case "btn4":
    //            // 合同签订
    //            directUrl = "~/App/Input/SaleContractForm.aspx";
    //            break;
    //        case "btn5":
    //            // 费用缴纳
    //            directUrl = "~/App/Input/PaymentUpdForm.aspx";
    //            break;
    //        case "btn6":
    //            // 礼品发放
    //            directUrl = "~/App/Search/SaleProcSrhForm.aspx";
    //            break;
    //        case "btn7":
    //            // 完成
    //            directUrl = "~/App/Search/SaleProcSrhForm.aspx";
    //            break;
    //        default:
    //            break;
    //    }
    //    if (!string.IsNullOrEmpty(Convert.ToString(this.ViewState["PROC_ID"])))
    //    {
    //        Context.Items["SALE_PROC_ID"] = this.ViewState["PROC_ID"];
    //    }
    //    // Server.Transfer(directUrl, true);
    //    ControllerUtils.Transfer(Context, directUrl, true);        
    //}

    // 是否有更新权限 check
    private Boolean checkAuthority(string procId, string emplyId, string role)
    {
        SaleProcessDao daoCheck = new SaleProcessDao();
        SaleProcessBean bean = new SaleProcessBean();
        bean.SaleProcId = Convert.ToInt32(procId);
        bean.EmployeeId = emplyId;
        bean.Role = role;
        IList list = daoCheck.CheckSaleProcessAu(bean);
        if (list == null || list.Count == 0) return false;
        return true;
    }

    // bind select data by procId
    private Boolean bindSelectData(string procId)
    {
        SaleProcessDao dao = new SaleProcessDao();
        SaleProcessBean beanSP = new SaleProcessBean();

        beanSP.SaleProcId = Convert.ToInt32(procId);
        beanSP = dao.FindBySaleProcess(beanSP);
        if (beanSP == null) return false;

        //lblProcId.Text = Convert.ToString(beanSP.SaleProcId);
        lblEmpId.Text = string.Format("{0} {1}", beanSP.EmployeeId, beanSP.EmployeeName);
        lblPersonMain.Text = beanSP.PersonNameMain;

        this.ViewState["CANCEL_FLG"] = beanSP.CancelFlg;
        //this.ViewState["CUR_STEP"] = beanSP.CurrentStep;

        // get gift list        
        SalesGiftBean beanSG = new SalesGiftBean();
        IList listGift = null;
        beanSG.SaleProcId = Convert.ToInt32(procId);
        listGift = dao.ListSalesGift(beanSG);
        viewGift.DataSource = listGift;
        viewGift.DataBind();

        //if (beanSP.CancelFlg) return false;

        return true;
    }

    //// set link button status
    //private void setLinkStatus()
    //{
    //    // page is allow edit
    //    if (this.ViewState["PROC_ID"] == null            
    //        || this.ViewState["CUR_STEP"] == null
    //        || this.ViewState["CANCEL_FLG"] == null            
    //        || (Boolean)this.ViewState["CANCEL_FLG"])
    //    {
    //        btnOk.Enabled = false;
    //        ((Design_MasterPage)this.Master).InfoMessage =
    //            HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0005").ToString();
    //    }

    //    // 判断是否已经 缴费登记
    //    if (Convert.ToInt32(this.ViewState["CUR_STEP"]) < SaleProcessDao.SALE_PROCESS_STEP_5)
    //    {
    //        btnOk.Enabled = false;
    //        ((Design_MasterPage)this.Master).InfoMessage =
    //            HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0902").ToString().Replace("{0}", "缴费登记");
    //    }
    //    //if (string.IsNullOrEmpty(Convert.ToString(this.ViewState["CUR_STEP"]))
    //    //    || Convert.ToInt32(this.ViewState["CUR_STEP"]) >= SaleProcessDao.SALE_PROCESS_STEP_6)
    //    //{
    //    //    ((Design_MasterPage)this.Master).InfoMessage =
    //    //        HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0004").ToString();
    //    //    btnOk.Enabled = false;
    //    //}

    //    // 流程跟踪 link button
    //    if (this.ViewState["CUR_STEP"] != null)
    //    {
    //        for (int i = 0; i <= Convert.ToInt32(this.ViewState["CUR_STEP"]); i ++)
    //        {
    //            if ((i + 1) < 8 )
    //                ((LinkButton)this.Master.FindControl("ContentPlaceHolder1").FindControl("lnkBtn" + (i + 1).ToString())).Enabled = true;
    //        }
    //    }
    //}

    // bind db data to selected controls
    private void bindDataToListControl(string ControlId, IList LstData)
    {
        if (LstData == null || LstData.Count == 0) return;

        foreach (CommonDictionaryBean bean in LstData)
        {
            if (this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId) is DropDownList)
            {
                ((DropDownList)this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId)).Items.Add(new ListItem(bean.Content, bean.DictNo.ToString()));
            }
            else if ((this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId) is CheckBoxList)
                || (this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId) is RadioButtonList))
            {
                ((ListControl)this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId)).Items.Add(new ListItem(bean.Content, bean.DictNo.ToString()));
            }
        }
    }

    // tab go 
    protected void lnkTab_Command(object sender, CommandEventArgs e)
    {
        string directUrl = "~/App/Input/PersonVst.aspx";
        switch (e.CommandName)
        {
            case "btn0":
                // 新建洽谈                
                directUrl = "~/App/Input/SaleProcessBeginForm.aspx";
                break;
            case "btn1":
                // 销售管理                
                directUrl = "~/App/Input/PersonVst.aspx";
                break;
            case "btn2":
                // 入住管理
                directUrl = "~/App/Input/MemberForm.aspx";
                break;
            case "btn3":
                // 购卡管理
                directUrl = "~/App/Input/RightPersonForm.aspx";
                break;
            case "btn4":
                // 客户移交                
                directUrl = "~/App/Input/ContractHabitationForm.aspx";
                break;
            case "btn1_1":
                // 上门拜访
                directUrl = "~/App/Input/PersonVstSrh.aspx";
                break;
            case "btn1_2":
                // 日常交流
                directUrl = "~/App/Input/PersonTel.aspx";
                break;
            case "btn1_3":
                // 礼品发放
                directUrl = "~/App/Input/SaleProcessPresentForm.aspx";
                break;
            case "btn6":
                // 资格审核
                directUrl = "~/App/Input/SaleProcessIndefinForm.aspx";
                break;
            default:
                break;
        }
        if (!string.IsNullOrEmpty(Convert.ToString(this.ViewState["PROC_ID"])))
        {
            Context.Items["SALE_PROC_ID"] = this.ViewState["PROC_ID"];
        }
        ControllerUtils.Transfer(this.Context, directUrl, false);
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        Context.Items["SALE_PROC_ID"] = this.ViewState["PROC_ID"];
        string directUrl = "~/App/Input/SaleCountForm.aspx";
        ControllerUtils.Transfer(this.Context, directUrl, false);
    }
}
